module Mil
  module FS

    # This class is a Block Object generator good for taking
    # a files contents and breaking it down into Block
    # Objects to be stored within the MilFS Object Store.
    class BlockGenerator

      # The size of the data segment used for Block generation.
      attr_accessor :block_size

      def initialize(block_size=nil)
	@block_size = block_size || 4096 

	true
      end

      # Generate an Array of Block from the data segment passed.
      # The Array order corrolates to the block ordering.
      def to_blocks(data)
	io = StringIO.new(data)
	blocks = []

	while seg = io.read(@block_size)
	  blocks << Block.new( seg )
	end

	blocks
      end

      # Generate a StringIO object from the array of blocks passed. The
      # assembly order is based on the order of the array starting with
      # element zero.
      def to_stream(blocks)
	raise ArgumentError unless blocks.is_a? Array

	io = StringIO.new

	blocks.each { |b|
	  size = io.write(b.data)
	  raise RuntimeError unless size == b.size.to_i
	}
	io.rewind

	io
      end
    end
  end
end
